package com.xhs.aspect;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;

/**
 * @desc: 接口日志切面，目的是将接口的入参、出参、异常等信息上报到SkyWalking链路追踪服务器上，以便我们进行日志分析
 * @projectName: spring-boot-skywalking
 * @author: xhs
 * @date: 2024-06-17 017 10:24
 * @version: JDK 1.8
 */

@Slf4j
@Aspect
@Component
public class ControllerLogAspect {

    public static final String BIG_STR_SUB_PATTERN = "(:s*\"[^,\":]{8192,}?\")";

    /**
     * API的切点,拦截所有controller
     */
    @Pointcut("execution(public * com.xhs.controller.*.*(..))")
    public void apiPointcut() {
    }

    /**
     * 在方法执行前进行参数判断、在方法执行后记录日志
     *
     * @param joinPoint 入参
     */
    @Around("apiPointcut()")
    public Object executeFaceAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        Object returnObj = null;
        Object[] parameters = joinPoint.getArgs();
        try {
            returnObj = joinPoint.proceed();
        } catch (Exception e) {
            log.error("SkyWalking aspect catch exception {}", TraceContext.traceId(), e);
            ActiveSpan.tag("异常", ExceptionUtil.getRootCauseMessage(e));
            throw e;
        } finally {
            if (parameters != null && parameters.length > 0) {
                for (int i = 0; i < parameters.length; i++) {
                    try {
                        Object nowObj = parameters[i];
                        if (nowObj instanceof ServletRequest) {
                            continue;
                        }
                        ActiveSpan.tag("入参" + i, replaceLog(JSON.toJSONString(nowObj)));
                    } catch (Exception ignore) {

                    }
                }
            }

            if (returnObj != null) {
                try {
                    ActiveSpan.tag("出参", replaceLog(JSON.toJSONString(returnObj)));
                } catch (Exception ignore) {

                }
            }
        }
        return returnObj;
    }

    /*
     * 格式化日志
     *
     * @param logStr 入参
     * @return String
     */
    public static String replaceLog(String logStr) {
        if (StringUtils.hasLength(logStr)) {
            return logStr.replaceAll(BIG_STR_SUB_PATTERN, ":\"*\"");
        }
        return StrUtil.EMPTY;
    }
}
